<?php

namespace app\api\controller\qixing;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use tests\thinkphp\library\think\dbTest;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 用户设备接口
 */
class Equipment extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 设备列表
     */
    public function list()
    {
        $list = Db::name('equipment')
                ->where('deleteTime is null')
                ->where('status',1)
                ->select();
        $list = collection($list)->toArray();
        foreach ($list as &$v){
            $v['sn_mac'] = sn_mac($v['sn_mac']);
        }
        $data = [
                    'list'  => $list
                ];
        $this->success('', $data);
    }


    /**
     * 用户设备列表
     */
    public function blist()
    {
        $userid = $this->auth->id;
        $params = $this->request->post();
        $page = isset($params['page'])&&is_numeric($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize'])&&is_numeric($params['pageSize']) ? $params['pageSize'] : 10;
        $list = Db::name('user_equipment')
                ->alias('ue')
                ->join('equipment e','e.id=ue.equipmentid')
                ->where('ue.userid',$userid)
                ->where('ue.deleteTime is null')
                ->field('ue.id as userbdid,ue.bname,ue.distance,ue.binding,e.*')
                ->limit(($page - 1)*$pageSize,$pageSize)
                ->select();
        foreach ($list as &$vv) {

            $vv['image'] = cdnurl($vv['image'],true);

            $vv['sn_mac'] = sn_mac($vv['sn']);

            //$vv['sn_mac'] = cdnurl($vv['sn'],true);
        }
        unset($vv);
        $deviceid = Db::name('user')->where('id',$userid)->value('deviceid');
        if (intval($deviceid)==0) {
            if (count($list)>0) {
                $deviceid = $list[0]['id'];
            }
            
        }
        $data = [
                    'list'  => $list,
                    'deviceid' => $deviceid
                ];
        $this->success('', $data);
    }

    /**
     * 用户设备详情
     */
    public function bdetail()
    {
        $userid = $this->auth->id;
        $equipmentid = $this->request->post('equipmentid');
        if (!$userid || !$equipmentid) {
            $this->error(__('Invalid parameters'));
        }
        $detail = Db::name('user_equipment')
                ->alias('ue')
                ->join('equipment e','e.id=ue.equipmentid')
                ->where(['ue.userid'=>$userid,'ue.equipmentid'=>$equipmentid])
                ->where('ue.deleteTime is null')
                ->field('ue.id as userbdid,ue.distance,ue.bname,ue.binding,e.*')
                ->find();
        $detail['totalmileage'] = $detail['totalmileage']>0?floatval(sprintf('%.1f',$detail['totalmileage']/10)):0;
        $detail['image'] = cdnurl($detail['image'],true);
        $data = [
                    'detail'  => $detail
                ];
        $this->success('', $data);
    }



    /**
     * 绑定设备
     * 通过蓝牙mac地址绑定设备
     */
    public function binding()
    {
        $userid = $this->auth->id;
        $sn = $this->request->post('sn');
        $sn = str_replace(':',"",$sn);
        if (!$userid || !$sn) {
            $this->error(__('Invalid parameters'));
        }
        $equipment = Db::name('equipment')->where(['sn'=>$sn])->find();

        if (!$equipment) {
            $idata = [
                'name'=> input('name'),
                'image'=> input('img')?input('img'):'/assets/img/bike.jpg',
                'sn' => $sn,
                'sn_mac' => sn_mac(input('sn_mac')),
                'bindinguserid' => $userid,
                'connectiontime' => date('Y-m-d H:i:s'),
                'createtime' => date('Y-m-d H:i:s')
            ];
            $equipmentid = Db::name('equipment')->insertGetId($idata);


            $data = [
                'userid'=>$userid,
                'equipmentid'=>$equipmentid,
                'bname'=> input('name'),
                'binding'=>1,
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
            Db::name('user_equipment')->insert($data);
        }else{
            $equipmentid = $equipment['id'];
            $bd = Db::name('user_equipment')->where(['equipmentid'=>$equipmentid,'userid'=>$userid,'binding'=>1,'deleteTime'=>null])->find();
            if (!$bd) {
                $data = [
                    'userid'=>$userid,
                    'equipmentid'=>$equipmentid,
                    'bname'=> input('name'),
                    'binding'=>1,
                    'createtime'=>date('Y-m-d H:i:s',time())
                ];
                Db::name('user_equipment')->insert($data);
                Db::name('equipment')->where(['id'=>$equipmentid])->update(['bindinguserid'=>$userid,'name'=>input('name')]);
            }
        }

        $this->success(__('Binding success'));
       /* if ($bd) {
            $this->error(__('The equipment has been binding'));
        }else{
            $equipmentname = Db::name('equipment')->where(['id'=>$equipmentid])->value('name');
            $bdrecord = Db::name('user_equipment')->where(['userid'=>$userid,'equipmentid'=>$equipmentid])->find();
            if ($bdrecord) {
               Db::name('user_equipment')->where('id',$bdrecord['id'])->update(['binding'=>1]);
            }else{
                $data = ['userid'=>$userid,'equipmentid'=>$equipmentid,'bname'=>$equipmentname,'binding'=>1,'createtime'=>date('Y-m-d H:i:s',time())];
               Db::name('user_equipment')->insert($data);
            }

            Db::name('equipment')->where('id',$equipmentid)->update(['bindinguserid'=>$userid]);
            $this->success(__('Binding success'));
        }*/
    }
    //修改设备图片
    public function modifyequipmentimg()
    {
        $equipmentid = input('id');
        $userid = $this->auth->id;
        Db::name('equipment')->where(['id'=>$equipmentid])->update(['image'=> input('img')?input('img'):'/assets/img/bike.jpg']);
        $this->success(__(''));
    }
    //更新设备数据
    public function updateequipment()
    {

        $input = input();
        //print_r($input);
        $userid = $this->auth->id;
        $sn = input('sn');
        $sn = str_replace(':',"",$sn);
        $data = [
            //'name' => !empty($input['name'])?$input['name']:'',//设备名字
            'model' => isset($input['model'])?$input['model']:'',//设备型号
            'curr_dangwei' => isset($input['curr_dangwei'])?$input['curr_dangwei']:'', //车辆当前助力档位（eg.1档）
            'curr_sudu' => isset($input['curr_sudu'])?$input['curr_sudu']:'', //车辆当前行使速度（单位0.1km/h）
            'avg_sudu' => isset($input['avg_sudu'])?$input['avg_sudu']:'', //车辆平均速度（单位0.1km/h）
            'zuida_sudui' => isset($input['zuida_sudui'])?$input['zuida_sudui']:'', //车辆最大速度（单位0.1km/h）
            'electricity' => isset($input['electricity'])?$input['electricity']:'', //电池电量百分比（0-100%）
            'totalmileage' => isset($input['totalmileage'])?$input['totalmileage']:'',//车辆行使总里程 km
            'canmileage' => isset($input['canmileage'])?$input['canmileage']:'', //车辆当前可骑行距离
            'danci' => isset($input['danci'])?$input['danci']:'',//车辆行驶单次里程
            'connectiontime' => date('Y-m-d H:i:s'),
            //'bindinguserid' => $userid,
            'sn' => $sn,
            'sn_mac' => input('sn'),
        ];
        $equipment = Db::name('equipment')->where(['sn'=>$sn])->find();
        if($equipment){
           Db::name('equipment')->where(['sn'=>$sn])->update($data);
        }else{
            Db::name('equipment')->insert($data);
        }



        $this->success(__(''));
    }

    /**
     * 绑定默认设备
     */
    public function bindingdefault()
    {
        $userid = $this->auth->id;
        $eid = $this->request->post('eid');
        $equipment = Db::name('equipment')->where(['bindinguserid'=>$userid,'id'=>$eid])->find();
        if ($equipment) {
            Db::name('user')->where('id',$userid)->update(['deviceid'=>$eid]);
            $this->success(__('Binding success'));
        }else{
            $this->error(__('The equipment has been binding'));
        }
    }

     /**
     * 解绑设备
     */
    public function unbundling()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        Db::name('user')->where('id',$id)->update(['deviceid'=>0]);
        Db::name('user_equipment')->where('id',$id)->update(['binding'=>0,'deleteTime'=>date('Y-m-d H:i:s')]);
        $equipmentid = Db::name('user_equipment')->where('id',$id)->value('equipmentid');
        Db::name('equipment')->where('id',$equipmentid)->update(['bindinguserid'=>0]);
        $this->success(__('Unbundling success'));
    }

    /**
     * 移除设备
     */
    public function removebundling()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        Db::name('user_equipment')->where('id',$id)->update(['binding'=>0,'deleteTime'=>date('Y-m-d H:i:s',time())]);
        $equipmentid = Db::name('user_equipment')->where('id',$id)->value('equipmentid');
        Db::name('equipment')->where('id',$equipmentid)->update(['bindinguserid'=>0]);
        $this->success(__('Successfully removed'));
    }

    /**
     * 设备重命名
     */
    public function rename()
    {
        $id = $this->request->post('id');
        $bname = $this->request->post('bname');
        if (!$id || !$bname) {
            $this->error(__('Invalid parameters'));
        }
        Db::name('user_equipment')->where('id',$id)->update(['bname'=>$bname]);
        $this->success(__('Rename the success'));
    }

}
